<?php
/**
 * Created by PhpStorm.
 * User: u
 * Date: 2018/11/22
 * Time: 17:34
 */

namespace common\services;
include 'baidu/BaiduBce.phar';
include 'baidu/SampleConf.php';

use Yii;
use BaiduBce\BceClientConfigOptions;
use BaiduBce\Util\Time;
use BaiduBce\Util\MimeTypes;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Services\Bos\BosClient;
use BaiduBce\Services\Bos\CannedAcl;
use BaiduBce\Services\Bos\BosOptions;
use BaiduBce\Auth\SignOptions;
use BaiduBce\Log\LogFactory;

class BaiduService
{
    private $accessKeyId;

    private $secretAccessKey;

    public function __construct($accessKeyId, $secretAccessKey)
    {
        $this->accessKeyId = $accessKeyId;
        $this->secretAccessKey = $secretAccessKey;
    }

    public static function uploadImages($files, $upload_img_type)
    {
        $BOS_TEST_CONFIG = Yii::$app->params['bos_test_config'];
        $client = new BosClient($BOS_TEST_CONFIG);
        $bucketName = Yii::$app->params['bucket_name'];

        //正式上传到百度BOS中
        $arr = explode('.', $_FILES['file']['name']);
        $upload_img_type_dir = Yii::$app->params['upload_images_types_dir'][$upload_img_type];
        $filename = $upload_img_type_dir.'/'.Date("Y/md", time()).'/'.time().rand(1000,9999).".".$arr[count($arr)-1];
        $res = $client->putObjectFromFile($bucketName,$filename, $files);
        if($res){
            //获取endpoint
            $ts = explode('//',$BOS_TEST_CONFIG['endpoint']);
            $data = array(
                'url'=> 'http://'.$bucketName.".".$ts[1]."/".$filename,
                'upload_img_type'=>$upload_img_type
            );

            return $data;
        }
        return $data = array('url'=> '','upload_img_type'=>$upload_img_type);

    }
    //直接上传原文件
    public static function uploadImageToBaidu($upload_img_type)
    {
        $BOS_TEST_CONFIG = Yii::$app->params['bos_test_config'];
        $client = new BosClient($BOS_TEST_CONFIG);
        $bucketName = Yii::$app->params['bucket_name'];
        $upfile = Yii::$app->params['upload_file_dir'];

        $arr = explode('.', $_FILES['file']['name']);
        $upload_img_type_dir = Yii::$app->params['upload_images_types_dir'][$upload_img_type];

        $filename = $upload_img_type_dir.'/'.Date("Y/md", time()).'/'.time().rand(1000,9999).".".$arr[count($arr)-1];
        $uploadFiles = $_FILES['file']['tmp_name'];
        $res = $client->putObjectFromFile($bucketName, $filename,$uploadFiles);
        if($res){
            //获取endpoint
            $ts = explode('//',$BOS_TEST_CONFIG['endpoint']);
            $data = array(
                'url'=> 'http://'.$bucketName.".".$ts[1]."/".$filename,
                'upload_img_type'=>$upload_img_type
            );

            return $data;
        }
        return $data = array('url'=> '','upload_img_type'=>$upload_img_type);
    }

}